#!/usr/bin/env python
"""
使用直接方式启动Inspector和MCP服务器进行测试
"""
import subprocess
import time
import webbrowser
import os
import sys
import signal
import socket
import random

def find_free_port():
    """找到一个可用的端口"""
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.bind(('localhost', 0))
    port = sock.getsockname()[1]
    sock.close()
    return port

def main():
    """启动MCP Inspector和服务器进程"""
    print("准备启动MCP Inspector和GitCode MCP服务器...\n")
    
    # 环境变量检查
    token = os.environ.get("GITCODE_TOKEN")
    if not token:
        print("⚠️ 警告: 未设置GITCODE_TOKEN环境变量")
        print("某些功能可能无法正常工作")
        should_continue = input("是否继续? (y/n): ").strip().lower()
        if should_continue != 'y':
            print("测试已取消")
            return
    
    # 首先清理可能存在的进程
    print("清理可能存在的旧进程...")
    try:
        subprocess.run(
            "pkill -f 'mcp-inspector' || true", 
            shell=True, 
            stdout=subprocess.DEVNULL, 
            stderr=subprocess.DEVNULL
        )
        time.sleep(1)
    except Exception as e:
        print(f"清理过程中出错: {e}")
    
    # 尝试直接运行MCP服务器
    print("\n步骤1: 启动GitCode MCP服务器...")
    
    # 确保设置了GITCODE_TOKEN环境变量
    env = os.environ.copy()
    
    server_process = subprocess.Popen(
        ["python", "-m", "gitcode_mcp.server"],
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        env=env,
        text=True,
        bufsize=1
    )
    
    print(f"服务器进程ID: {server_process.pid}")
    
    # 等待服务器启动
    server_ready = False
    for _ in range(20):  # 等待最多20秒
        line = server_process.stdout.readline().strip()
        if line:
            print(f"服务器输出: {line}")
            if "GitCode MCP服务器已初始化" in line or "GitCode API客户端已初始化" in line:
                server_ready = True
                break
        time.sleep(0.5)
    
    if not server_ready:
        print("❌ MCP服务器未能在预期时间内启动")
        server_process.terminate()
        return
    
    print(f"\n✅ GitCode MCP服务器已成功启动!")
    
    print("\n步骤2: 在浏览器中打开MCP Inspector...")
    
    try:
        # 尝试在浏览器中直接打开Inspector
        webbrowser.open("http://localhost:5173")
        
        print("\n🔍 测试指南:")
        print("1. 在浏览器中的Inspector界面:")
        print("   - 点击'Connect to server'按钮")
        print("   - 在'Transport type'选择'stdio'")
        print("   - 在'server command'字段中输入: python -m gitcode_mcp.server")
        print("   - 点击'Connect'按钮")
        print("2. 连接成功后:")
        print("   - 在'Tools'标签中测试可用工具")
        print("   - 在'Resources'标签中查看可用资源")
        print("   - 在'Prompts'标签中查看提示模板")
        
        print("\n如果Inspector页面无法打开，请手动访问:")
        print("- http://localhost:5173")
        print("- 或者 http://127.0.0.1:5173")
        print("- 或尝试其他端口: 5174, 5175, 3000, 3001, 8000")
        
        print("\n可以同时尝试直接命令行方式运行(在新终端中):")
        print("mcp dev src/gitcode_mcp/server.py")
        
        print("\n按Ctrl+C可随时终止测试")
        
        # 等待用户终止
        try:
            print("\n服务器正在运行中...")
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n接收到终止信号，正在关闭...")
    finally:
        # 清理进程
        print("清理进程...")
        if server_process and server_process.poll() is None:
            server_process.terminate()
            try:
                server_process.wait(timeout=3)
            except subprocess.TimeoutExpired:
                server_process.kill()
                
        print("测试完成")

if __name__ == "__main__":
    main() 